package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"time"
)

var (
	started = false
	// 添加 flag 参数
	serverAddr = flag.String("server", "localhost:8080", "服务器地址，格式为 host:port")
	interval   = flag.Duration("interval", time.Second, "发送消息的时间间隔")
	timeout    = flag.Duration("timeout", 5*time.Second, "读写超时时间")

	total   = 0
	sendErr = 0
	resErr  = 0
)

func checkClient() {
	time.Sleep(10 * time.Second)
	if !started {
		startClient()
	}
	checkClient()
}

func startClient() {
	// 连接服务器
	conn, err := net.Dial("tcp", *serverAddr)
	if err != nil {
		log.Printf("连接服务器失败: %v\n", err)
		return
	}
	started = true
	defer func() {
		// 设置写入超时
		_ = conn.SetWriteDeadline(time.Now().Add(*timeout))
		// 发送关闭信号
		_, err = conn.Write([]byte("quit"))
		if err != nil {
			fmt.Printf("发送退出信号失败: %v\n", err)
		}
		_ = conn.Close()
		started = false
	}()

	fmt.Println("已连接到服务器")

	buffer := make([]byte, 4)
	i := 0
	for {
		i++
		if i > 10000 {
			i = 1

			total = 0
			sendErr = 0
			resErr = 0
		}

		// 设置写入超时
		_ = conn.SetWriteDeadline(time.Now().Add(*timeout))

		// 记录发送时间
		startTime := time.Now()

		// 发送消息
		message := "Ping"
		_, err = conn.Write([]byte(message))
		if err != nil {
			sendErr++
			outRes(i, startTime)
			continue
		}

		// 设置读取超时
		_ = conn.SetReadDeadline(time.Now().Add(*timeout))

		// 接收响应
		_, err = conn.Read(buffer)
		if err != nil {
			resErr++
			outRes(i, startTime)
			continue
		}
		total++
		outRes(i, startTime)
	}
}

func outRes(i int, startTime time.Time) {
	fmt.Printf("发送数: %d 接收数: (%d/%d) 失败:（发送%d/接收%d） 往返时间: %dms\n", i, total, i-total, sendErr, resErr, time.Since(startTime).Milliseconds())
	// 使用flag参数设置的间隔时间
	time.Sleep(*interval)
}
